import requests
import sqlite3
import time
from datetime import datetime

DB_FILE = 'accounts_data.db'
API_URL = 'http://47.122.94.218:5000/api/accounts?page=1&size=500'
INTERVAL_SECONDS = 1200  # 30分钟

def init_db():
    conn = sqlite3.connect(DB_FILE)
    c = conn.cursor()
    c.execute('''
    CREATE TABLE IF NOT EXISTS accounts (
        id INTEGER PRIMARY KEY,
        email TEXT,
        username TEXT,
        password TEXT,
        invite_code TEXT,
        reg_time TEXT,
        status TEXT,
        is_deleted BOOLEAN,
        err_msg TEXT,
        fetched_at TEXT
    )
    ''')
    conn.commit()
    conn.close()

def fetch_and_store():
    try:
        resp = requests.get(API_URL)
        resp.raise_for_status()
        data = resp.json()['data']
        print(data)


        if not isinstance(data, list):
            print(f"[{datetime.now()}] 响应不是预期的列表格式，实际内容：{type(data)}")
            return

        conn = sqlite3.connect(DB_FILE)
        c = conn.cursor()
        for item in data:
            # 用 INSERT OR REPLACE 保证id唯一且更新
            c.execute('''
                INSERT OR REPLACE INTO accounts
                (id, email, username, password, invite_code, reg_time, status, is_deleted, err_msg, fetched_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ''', (
                item.get('id'),
                item.get('email'),
                item.get('username'),
                item.get('password'),
                item.get('invite_code'),
                item.get('reg_time'),
                item.get('status'),
                int(item.get('is_deleted', False)),
                item.get('err_msg'),
                datetime.now().isoformat()
            ))
        conn.commit()
        conn.close()
        print(f"[{datetime.now()}] {len(data)} 条数据已存入SQLite.")
    except Exception as e:
        print(f"[{datetime.now()}] 获取或存储数据失败: {e}")

def main():
    init_db()
    while True:
        fetch_and_store()
        time.sleep(INTERVAL_SECONDS)

if __name__ == '__main__':
    main()